﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using ZSDDBHelper;
using DBModel;
using Utility;
using System.Web.UI;
using System.Net;
using System.Net.Sockets;
using System.Web;
namespace BllService
{

    public abstract class DbCommon
    {

        public Action<object> RefreshCacheData;
        public ResultModel result = new ResultModel();
        private ZSDDBHelper.DBHelper _DbHelper = new DBHelper();
        public List<ConditionModel> listCondition = new List<ConditionModel>();

        /// <summary>
        /// 获取当前用户客户端ip
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentUserIp()
        {
            string ipv4 = String.Empty;
            foreach (IPAddress ip in Dns.GetHostAddresses(GetClientIP()))
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    ipv4 = ip.ToString();
                    break;
                }
            }
            if (ipv4 != String.Empty)
            {
                return ipv4;
            }
            // 利用 Dns.GetHostEntry 方法，由获取的 IPv6 位址反查 DNS 纪录，
            // 再逐一判断何者为 IPv4 协议，即可转为 IPv4 位址。
            foreach (IPAddress ip in Dns.GetHostEntry(GetClientIP()).AddressList)
            //foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    ipv4 = ip.ToString();
                    break;
                }
            }
            return ipv4;
        }

        public static string GetClientIP()
        {
            if (null == HttpContext.Current.Request.ServerVariables["HTTP_VIA"])
            {
                return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            }
        }
        #region  增删改管理
        /// <summary>
        ///  支持 批量添加
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="model"> model 支持批量添加 </param>
        /// <param name="conn"></param>
        /// <param name="tran"></param>
        /// <param name="baseType"></param>
        /// <param name="isLog">是否需要加入日志</param>
        /// <returns></returns>
        public virtual ResultModel InserTable(string TableName, object model, IDbConnection conn = null, IDbTransaction tran = null, DataBaseType baseType = DataBaseType.NONE, bool isCommit = true, bool isLog = true)
        {
            try
            {
                var bl = _DbHelper.InsertTableDB(TableName, model, conn, tran, baseType, isCommit);
                if (bl)
                {
                    result.code = 1;
                    result.msg = "数据插入成功!";
                    //插入日志
                    if (isLog)
                    {
                        var logmodel = new SysOperationLogModel();
                        logmodel.OperationType = "新增";
                        logmodel.FunctionName = "新增";
                        logmodel.ExecutionResult = "成功";
                    }
                }
                else
                {
                    result.code = 0;
                    result.msg = "数据插入失败!";
                    //插入日志
                    if (isLog)
                    {
                        var logmodel = new SysOperationLogModel();
                        logmodel.OperationType = "新增";
                        logmodel.FunctionName = "新增";
                        logmodel.ExecutionResult = "失败";
                    }
                }
            }
            catch (Exception ex)
            {
                result.code = -1;
                result.msg = ex.Message;

                //插入日志
                var logmodel = new SysOperationLogModel();
                logmodel.OperationType = "新增";
                logmodel.FunctionName = "新增";
                logmodel.ExecutionResult = ex.Message;            }
            return result;
        }

        /// <summary>
        ///  支持 批量添加日志
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="model"> model 支持批量添加 </param>
        /// <param name="conn"></param>
        /// <param name="tran"></param>
        /// <param name="baseType"></param>
        /// <returns></returns>
        public virtual void InserSysOperationLogTable(string TableName, object model, IDbConnection conn = null, IDbTransaction tran = null, DataBaseType baseType = DataBaseType.NONE, bool isCommit = true)
        {
            try
            {
                var bl = _DbHelper.InsertTableDB(TableName, model, conn, tran, baseType, isCommit);
                if (bl)
                {
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="model"></param>
        /// <param name="listCondition"></param>
        /// <returns></returns>
        public virtual ResultModel UpdateTable(string TableName, object model, List<ConditionModel> listCondition, IDbConnection conn = null, IDbTransaction tran = null, DataBaseType baseType = DataBaseType.NONE, bool isCommit = true)
        {
            try
            {
                var bl = _DbHelper.UpdateTableDB(TableName, model, listCondition, conn, tran, baseType, isCommit);
                if (bl)
                {
                    result.code = 1;
                    result.msg = "数据更新成功!";
                    //插入日志
                    var logmodel = new SysOperationLogModel();
                    logmodel.OperationType = "修改";
                    logmodel.FunctionName = "修改";
                    logmodel.ExecutionResult = "成功";
                }
                else
                {
                    result.code = 0;
                    result.msg = "数据更新失败!";
                    //插入日志
                    var logmodel = new SysOperationLogModel();
                    logmodel.OperationType = "新增";
                    logmodel.FunctionName = "新增";
                    logmodel.ExecutionResult = "失败";
                }
            }
            catch (Exception ex)
            {
                result.code = -1;
                result.msg = ex.Message;
                //插入日志
                var logmodel = new SysOperationLogModel();
                logmodel.OperationType = "新增";
                logmodel.FunctionName = "新增";
                logmodel.ExecutionResult = ex.Message;
            }
            return result;
        }
        /// <summary>
        ///  数据更新ByKey
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="model"></param>
        /// <param name="conn"></param>
        /// <param name="tran"></param>
        /// <param name="baseType"></param>
        /// <param name="isCommit"> 默认事务提交 </param>
        /// <returns></returns>
        public virtual ResultModel UpdateTableByKey(string TableName, object model, IDbConnection conn = null, IDbTransaction tran = null, DataBaseType baseType = DataBaseType.NONE, bool isCommit = true)
        {

            try
            {
                var bl = _DbHelper.UpdateTableWhereByKey(TableName, model, conn, tran, baseType, isCommit);

                if (bl)
                {
                    result.code = 1;
                    result.msg = "数据更新成功!";
                    //插入日志
                    var logmodel = new SysOperationLogModel();
                    logmodel.OperationType = "修改";
                    logmodel.FunctionName = "修改";
                    logmodel.ExecutionResult = "成功";
                }
                else
                {
                    result.code = 0;
                    result.msg = "数据更新失败!";
                    //插入日志
                    var logmodel = new SysOperationLogModel();
                    logmodel.OperationType = "修改";
                    logmodel.FunctionName = "修改";
                    logmodel.ExecutionResult = "失败";
                }
            }
            catch (Exception ex)
            {
                result.code = -1;
                result.msg = ex.Message;
                //插入日志
                var logmodel = new SysOperationLogModel();
                logmodel.OperationType = "新增";
                logmodel.FunctionName = "新增";
                logmodel.ExecutionResult = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strSQL"></param>
        /// <param name="model"></param>
        /// <param name="conn"></param>
        /// <param name="tran"></param>
        /// <param name="baseType"></param>
        /// <param name="isCommit"></param>
        /// <returns></returns>
        public virtual ResultModel UpdateTableBySql(string strSQL, object model, IDbConnection conn = null, IDbTransaction tran = null, DataBaseType baseType = DataBaseType.NONE, bool isCommit = true)
        {
            try
            {
                var bl = _DbHelper.UpdateTableByUserDefSQL(strSQL, model, baseType, conn, tran, isCommit);

                if (bl)
                {
                    result.code = 1;
                    result.msg = "数据更新成功!";
                    //插入日志
                    var logmodel = new SysOperationLogModel();
                    logmodel.OperationType = "修改";
                    logmodel.FunctionName = "修改";
                    logmodel.ExecutionResult = "成功";
                }
                else
                {
                    result.code = 0;
                    result.msg = "数据更新失败!";
                    //插入日志
                    var logmodel = new SysOperationLogModel();
                    logmodel.OperationType = "修改";
                    logmodel.FunctionName = "修改";
                    logmodel.ExecutionResult = "失败";
                }
            }
            catch (Exception ex)
            {
                result.code = 0;
                result.msg = ex.Message;
                //插入日志
                var logmodel = new SysOperationLogModel();
                logmodel.OperationType = "修改";
                logmodel.FunctionName = "修改";
                logmodel.ExecutionResult = ex.Message;
            }
            return result;
        }

        /// <summary>
        ///  数据删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="TableName"></param>
        /// <param name="listCondition"></param>
        /// <param name="conn"></param>
        /// <param name="tran"></param>
        /// <param name="baseType"></param>
        /// <param name="isCommit"></param>
        /// <returns></returns>
        public virtual ResultModel DeleteTable(string TableName, List<ConditionModel> listCondition, IDbConnection conn = null, IDbTransaction tran = null, DataBaseType baseType = DataBaseType.NONE, bool isCommit = true)
        {
            result = new ResultModel();
            try
            {
                var bl = _DbHelper.DeteleTableDB(TableName, listCondition, conn, tran, baseType, isCommit);
                if (bl)
                {
                    result.code = 1;
                    result.msg = "数据删除成功!";
                    //插入日志
                    var logmodel = new SysOperationLogModel();
                    logmodel.OperationType = "删除";
                    logmodel.FunctionName = "删除";
                    logmodel.ExecutionResult = "成功";
                }
                else
                {
                    result.code = 0;
                    result.msg = "数据删除失败!";
                    //插入日志
                    var logmodel = new SysOperationLogModel();
                    logmodel.OperationType = "删除";
                    logmodel.FunctionName = "删除";
                    logmodel.ExecutionResult = "失败";
                }
            }
            catch (Exception ex)
            {
                result.code = -1;
                result.msg = ex.Message;
                //插入日志
                var logmodel = new SysOperationLogModel();
                logmodel.OperationType = "删除";
                logmodel.FunctionName = "删除";
                logmodel.ExecutionResult = ex.Message;
            }
            return result;
        }
        #endregion

        #region 数据查询
        public virtual List<T> SearchData<T>(string strTable) where T : new()
        {
            var t = _DbHelper.QueryTableDB<T>(strTable);
            return t;
        }

        public virtual DataTable SearchDataList(string QuerySQL, object Condition, IDbConnection con = null, IDbTransaction Trcon = null, DataBaseType DataType = DataBaseType.NONE)
        {

            var t = _DbHelper.QueryTableByUserDefSql(QuerySQL, Condition, con, Trcon, DataType);
            return t;
        }

        public virtual List<T> SearchDataList<T>(string QuerySQL, object Condition, IDbConnection con = null, IDbTransaction Trcon = null, DataBaseType DataType = DataBaseType.NONE) where T : new()
        {

            var t = _DbHelper.QueryTableByUserDefSql<T>(QuerySQL, Condition, con, Trcon, DataType);
            return t;
        }

        public virtual List<T> SearchData<T>(SearchSQLModel searchModel, object ParamModel = null, IDbConnection con = null, IDbTransaction Trcon = null, DataBaseType DataType = DataBaseType.NONE) where T : new()
        {

            var t = _DbHelper.QueryTableDB<T>(searchModel, ParamModel, con, Trcon, DataType);

            return t;
        }

        



        /// <summary>
        /// 单表数据查询 说明: 返回实体列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="TableName"></param>
        /// <param name="ListModel">查询过滤条件/值</param>
        /// <param name="con"></param>
        /// <param name="Trcon"></param>
        /// <param name="DataType"></param>
        /// <param name="SortRule"></param>
        /// <returns></returns>
        public virtual List<T> SearchData<T>(string TableName, List<ConditionModel> ListModel, IDbConnection con = null, IDbTransaction Trcon = null, DataBaseType DataType = DataBaseType.NONE, string SortRule = "", bool isLog = true)
        {
            if (isLog)
            {
                var logmodel = new SysOperationLogModel();
                logmodel.OperationType = "查询";
                logmodel.FunctionName = "查询";
                logmodel.ExecutionResult = "成功";
            }

            return _DbHelper.QueryTableDB<T>(TableName, ListModel, con, Trcon, DataType, SortRule);
        }

        #endregion

        #region  序列化

        /// <summary>
        ///  对象系列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public virtual string SerializeObject(object obj)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
        }


        /// <summary>
        ///  对象系列化 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public virtual string SerializeToResultModel(object obj, int count = 1000, int code = 1, string msg = "成功")
        {
            ResultModel result = new ResultModel();
            result.code = code;
            result.data = obj;
            result.msg = msg;
            result.count = count;
            return Newtonsoft.Json.JsonConvert.SerializeObject(result);

        }

        /// <summary>
        ///  反序列化
        /// </summary>
        /// <param name="Json"></param>
        /// <returns></returns>
        public virtual object DeserializeObject(string Json)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject(Json);
        }
        /// <summary>
        ///  反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Json"></param>
        /// <returns></returns>
        public virtual T DeserializeObject<T>(string Json)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(Json);
        }

        #endregion

        #region 失败输出
        public virtual string ExceptionReturn(Exception ex)
        {

            result.code = -1;
            result.msg = ex.Message;
            result.data = "";
            return SerializeObject(result);

        }
        #endregion

        #region 对象映射
        /// <summary>
        /// 反射实现两个类的对象之间相同属性的值的复制
        /// 适用于初始化新实体
        /// </summary>
        /// <typeparam name="D">返回的实体</typeparam>
        /// <typeparam name="S">数据源实体</typeparam>
        /// <param name="s">数据源实体</param>
        /// <returns>返回的新实体</returns>
        public static D Mapper<D, S>(S s) where D : new() where S : new()
        {
            D d = Activator.CreateInstance<D>(); //构造新实例
            try
            {
                var Types = s.GetType();//获得类型  
                var Typed = typeof(D);
                foreach (System.Reflection.PropertyInfo sp in Types.GetProperties())//获得类型的属性字段  
                {
                    foreach (System.Reflection.PropertyInfo dp in Typed.GetProperties())
                    {
                        if (dp.Name == sp.Name && dp.PropertyType == sp.PropertyType && dp.Name != "Error" && dp.Name != "Item")//判断属性名是否相同  
                        {
                            dp.SetValue(d, sp.GetValue(s, null), null);//获得s对象属性的值复制给d对象的属性  
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return d;
        }
        #endregion
       

    }

}